package com.bawei.detail.model

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bawei.common.entity.MovieVideoEntity
import com.bawei.detail.api.DetailServerApi
import com.bawei.network.BaseResponse
import com.bawei.network.HttpInterceptorType
import com.bawei.network.HttpManager

/**
 * Author: Jason Zhang
 * Date: 2024/9/24
 * Desc: Paging数据源对象
 */
class MovieDetailPagingSource constructor(private val typeId: Int = -1, private val pageSize: Int = 10): PagingSource<Int, MovieVideoEntity>() { //第一个参数为页面Key，第二各参数为数据实体对象

    /**
     * 获取刷新页面Key
     */
    override fun getRefreshKey(state: PagingState<Int, MovieVideoEntity>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1)?: anchorPage?.nextKey?.minus(1) //相当于PageIndex
        }
    }

    /**
     * 加载/请求数据
     */
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MovieVideoEntity> {
        try {
            val currentPage = params.key ?: 1 //默认从第一页数据加载
            val loadSize = params.loadSize //加载多少条数据

            val apiServerApi = HttpManager.createApiServer<DetailServerApi>(DetailServerApi::class.java, HttpInterceptorType.INTERCEPTOR)
            //推荐视频
            var response: BaseResponse<List<MovieVideoEntity>> = if (typeId == -1){
                apiServerApi?.getRecommendMultiVideo(currentPage, pageSize)!!
            } else {  //分类视频
                apiServerApi?.getMultiVideoByTypeId(typeId, currentPage, pageSize)!!
            }
            //使用解构获取数据字段
            val (code, data, msg) = response

            //计算前一页的key
            val prePageKey: Int? = (currentPage - 1).run { if (this == 0) null else this }

            //计算下一页的Key
            val nextPageKey: Int? = when{
                loadSize > pageSize -> loadSize / pageSize + 1 //出现重复数据时需要处理
                code == 0 -> currentPage + 1
                else -> null
            }

            //返回数据对象
            return LoadResult.Page(data, prePageKey, nextPageKey)
        }catch (e: Exception){
            e.printStackTrace()
            return LoadResult.Error(e)

        }
    }


}